package com.dhcc.android.base.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Environment;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.view.MyLoadingDialog;

import java.io.File;
import java.io.FileWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;

public class CrashHandler implements UncaughtExceptionHandler {

    public static final String TAG = "CrashHandler";

    // 系统默认的UncaughtException处理类
    private UncaughtExceptionHandler mDefaultHandler;
    // CrashHandler实例
    private static CrashHandler INSTANCE = new CrashHandler();
    // 程序的Context对象
    private Context mContext;

    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler() {
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {

            }
            // 退出程序
            new MSApplication().exit();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        }

    }

    private void saveData() {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(mContext);
        Editor editor = sp.edit();
        editor.putBoolean(MSApplication.EXCEPTION_FLAG, true);
        editor.commit();
    }

    private void saveLog(Throwable ex) {
        String logdir;
        if (Environment.getExternalStorageDirectory() != null) {
            SharedPreferences sp = PreferenceManager
                    .getDefaultSharedPreferences(mContext);
            logdir = sp.getString(MSApplication.TASK_SAVE_PATH,
                    FileUtil.getSavePath()) + File.separator;
            File file = new File(logdir);
            boolean mkSuccess;
            if (!file.isDirectory()) {
                mkSuccess = file.mkdirs();
                if (!mkSuccess) {
                    mkSuccess = file.mkdirs();
                }
            }

            try {
                FileWriter fw = new FileWriter(logdir + File.separator + "error.log", true);
                fw.write(new Date() + "\n");
                StackTraceElement[] stackTrace = ex.getStackTrace();
                fw.write(ex.getMessage() + "\n");

                for (int i = 0; i < stackTrace.length; i++) {
                    fw.write("file:" + stackTrace[i].getFileName() + " class:" + stackTrace[i].getClassName()
                            + " method:" + stackTrace[i].getMethodName() + " line:" + stackTrace[i].getLineNumber()
                            + "\n");
                }
                fw.write("\n");
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        Log.e(TAG, "error : ", ex);
        String exStr = translateException(ex);
        String str = "应用出错,请联系管理员,正在退出...";
        if (exStr != null) {
            str = exStr + ",正在退出...";
        } else {
            //系统回收屏幕资源的bug
            str = "出现不可预知错误，请联系天合数维！和数据包制作方协调解决。" + ",\n程序正在退出...";
        }
        final String note = str;
        // 使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                StringUtil.dismissDialog(Constants.DIALOG);
                //edit zhoudan 20150626
                //将toast改为dialog
                if (MSApplication.instance().getmList().size() > 0) {
                    Dialog dialog = MyLoadingDialog.createLoadingDialog(MSApplication.instance().getmList().get(MSApplication.instance().getmList().size() - 1), note);
                    dialog.show();
                } else {
        Toast.makeText(mContext, note,
                Toast.LENGTH_LONG).show();

    }
    Looper.loop();
}
}.start();

        // 在此可执行其它操作，如获取设备信息、执行异常登出请求、保存错误日志到本地或发送至服务端
        saveData();
        saveLog(ex);

        return true;
    }


    private String translateException(Throwable ex) {
        Throwable cause = ex.getCause();
        if (cause != null) {
            String exClass = cause.getClass().getName();
            System.out.println("-Exception-:" + exClass);
            String s = exClass;
            if (exClass.contains("NullPointerException")) {
                s = "空指针异常";
            } else if (exClass.contains("ClassNotFoundException")) {
                s = "指定的类不存在异常";
            } else if (exClass.contains("ArrayIndexOutOfBoundsException")) {
                s = "数组下标越界异常";
            } else if (exClass.contains("ClassCastException")) {
                s = "类型强制转换异常";
            } else if (exClass.contains("FileNotFoundException")) {
                s = "文件未找到异常";
            } else if (exClass.contains("NumberFormatException")) {
                s = "数字格式异常";
            } else if (exClass.contains("SQLException")) {
                s = "操作数据库异常";
            } else if (exClass.contains("IOException")) {
                s = "输入输出异常";
            } else if (exClass.contains("IndexOutOfBoundsException")) {
                s = "索引越界异常";
            } else if (exClass.contains("StringIndexOutOfBoundsException")) {
                s = "字符串索引越界异常";
            } else if (exClass.contains("StackOverflowError")) {
                s = "堆栈溢出错误";
            } else if (exClass.contains("OutOfMemoryError")) {
                s = "内存不足错误";
            }
            return s;

        } else {
            String s = ex.getMessage();
            if (s.contains("no such table: ")) {
                s = "数据包有误，缺少表，请联系数据生产商！";
                return s;
            } else if (s.toLowerCase().contains("trying to use a recycled bitmap android.graphics.bitmap")) {
                s = "您的设备太霸道了!!!\n(它自己回收了自己正在使用的图片资源)，\n请联系硬件厂商，他们可能需要您提供日志文件,\n在SurveyPlus下的error文件!";
                return s;
            }
            return null;
        }
    }

}
